package com.mtt.thirdapi.filter;


import com.mtt.thirdapi.common.util.ParseMD5;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j

@WebFilter(urlPatterns = { "/yanxuan/*"})

public class SignAutheFilter implements Filter {
    private String secret="songjuzhi";
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            String authorization = request.getHeader("Authorization");
            log.info("getted Authorization is ---> " + authorization);
            String[] info = authorization.split(",");
            // 获取客户端ip
            //String ip = IpUtil.getIpAddr(request);
            //logger.info("getted ip is ---> " + ip);
            // 获取几个相关的字符
            // 由于authorization类似于
            // cardid="1234554321",timestamp="9897969594",signature="a69eae32a0ec746d5f6bf9bf9771ae36"
            // 这样的,所以逻辑是下面这样的
            int appKeyIdnex = info[0].indexOf("=") + 2;
            String appKey = info[0].substring(appKeyIdnex, info[0].length() - 1);
            log.info("appKey is ---> " + appKey);

            int appSecretIndex = info[1].indexOf("=") + 2;
            String appSecret = info[1].substring(appSecretIndex, info[1].length() - 1);
            String tmptString = ParseMD5.MD5EncodeForHex( secret , "UTF-8")
                    .toUpperCase();
            log.info("getted ciphertext is ---> {}, correct ciphertext is ---> {}",
                    appSecret, tmptString);

            // 判断该ip是否合法
            /*boolean containIp = false;
            for (String string : permittedIps) {
                if (string.equals(ip)) {
                    containIp = true;
                    break;
                }
            }
*/
            // 再判断Authorization内容是否正确,进而判断是否最终放行
          //  boolean couldPass = containIp && tmptString.equals(signature);
            boolean couldPass =tmptString.equals(appSecret);
            if (couldPass) {
                // 放行
                filterChain.doFilter(request, response);
                return;
            }
            response.sendError(403, "Forbidden");
        } catch (Exception e) {
            log.error("AxbAuthenticationFilter -> " + e.getMessage(), e);
            response.sendError(403, "Forbidden");
        }
    }
}

/**
 * 辅助类 ---> 变相使得可以多次通过(不同)流读取相同数据
 *
 * @author JustryDeng
 * @DATE 2018年9月11日 下午7:13:52
 */
class MyRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public String getBody() {
        return body;
    }

    public MyRequestWrapper(final HttpServletRequest request) throws IOException {
        super(request);
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        body = sb.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
        return new ServletInputStream() {
            /*
             * 重写ServletInputStream的父类InputStream的方法
             */
            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}